'use strict';
const Service = require('egg').Service;

class configJsonService extends Service {
  async setConfigJson(params) {
    const ctx = this.ctx;
    const now = new Date();
    const { configJson } = params;
    const result = await ctx.model.ConfigJson.findOne({
      attributes: [ 'id' ],
      raw: true,
      where: {
        id: 1,
      },
    });
    const obj = {
      id: 1,
      configJson,
      createdTime: now,
      updatedTime: now,
    };
    if (result) {
      const model = await ctx.model.ConfigJson.update(obj, {
        where: {
          id: 1,
        },
      });
      return await ctx.service.returnBody.index(model ? {} : null, '配置失败！');
    }
    const model = await ctx.model.ConfigJson.create(obj);
    return await ctx.service.returnBody.index(model ? {} : null, '配置失败！');
  }
  async getConfigJson() {
    const ctx = this.ctx;
    const result = await ctx.model.ConfigJson.findOne({
      attributes: [ 'configJson' ],
      raw: true,
      where: {
        id: 1,
      },
    });
    return await ctx.service.returnBody.index(result || { configJson: null });
  }
}

module.exports = configJsonService;
